// http static file server

let startStaticServer = require('./static-server')
startStaticServer()

// websocket server

let WebSocket = require('ws')
let WebSocketServer = WebSocket.Server;
let wss = new WebSocketServer({port: 3001})

let logoID = 0
let allUsers = {}

const LOGO_SIZE = 12

function getLogoName() {

    if (++logoID === LOGO_SIZE) {
        logoID = 1
    }

    if (logoID < 10) {
        return './images/logos/logo0' + logoID + '.png'
    } else {
        return './images/logos/logo' + logoID + './png'
    }
}

function broadcast() {
    
    let userNames = []

    console.log('[SYS] Current Users: ')

    for (let user in allUsers) {
        userNames.push({
            name: user,
            logo: allUsers[user].logo,
            status: allUsers[user].status
        })
        console.log('[system] user ', user)
    }

    userList = JSON.stringify({
        type: 'UserList',
        value: userNames
    })

    for (let user in allUsers) {
        if (allUsers[user].socket.readyState === WebSocket.OPEN) {
            allUsers[user].socket.send(userList)
        }
    }
}

function dispatchMessage(ws, message) {

    let o = JSON.parse(message)
    console.log(o)

    switch (o.type) {
        case 'Login':
            console.log('[sys] Login')
            console.log('[sys] get a new user')
            console.log('[sys] username is ', o.username)
            if (o.username in allUsers) {
                if (allUsers[o.username].status === 'offline') {
                    allUsers[o.username].status = 'online';
                    allUsers[o.username].socket = ws;
                } else {
                    ws.send(JSON.stringify({
                        type: 'Login',
                        value: 'invalid'
                    }))
                    return
                }
            } else {
                allUsers[o.username] = {
                    status: 'online',
                    socket: ws,
                    logo: getLogoName()
                }
            }
            ws.send(JSON.stringify({
                type: 'Login',
                value: 'valid'
            }))
            broadcast()
            break
        case 'ChatMessage':
            console.log('[sys] ChatMessage')
            console.log('[sys] ', o.from, ' --> ', o.to)
            console.log('[sys] message is ', o.message)
            if (o.to in allUsers && allUsers[o.to].socket &&
                    allUsers[o.to].socket.readyState === WebSocket.OPEN) {
                allUsers[o.to].socket.send(message)
            } else {
                console.warn('[error] unkown user ', o.to)
            }
            break
        default:
            console.log('invalid message')
    }
}

wss.on('connection', ws => {

    console.log('new connection') 
    
    ws.on('message', message => {
        dispatchMessage(ws, message)
    })
    
    ws.on('close', () => {
        for (let user in allUsers) {
            if (allUsers[user].socket === ws) {
                console.log("client ", user, " disconneted")
                allUsers[user].status = 'offline'
                broadcast()
                break
            }
        }
    })

    ws.on('error', () => {
        console.log('[sys] an error occur!')
    })
})
